package com.zou.controller.backstage;

import com.zou.commons.constants.Constants;
import com.zou.commons.domain.ReturnObject;
import com.zou.pojo.Manager;
import com.zou.service.ManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
public class LoginController {
    @Autowired
    private ManagerService managerService;

    /**
     * 进入登录页
     *
     * @return
     */
    @GetMapping("/backstage/login")
    public String toLogin() {
        return "backstage/login.html";
    }

    /**
     * 接收请求参数返回登录结果
     *
     * @param name
     * @param password
     * @param captcha
     * @param session
     * @return
     */
    @PostMapping("/backstage/login")
    public @ResponseBody
    Object login(String name, String password, String captcha, HttpSession session) {
        //根据结果，生成响应信息
        ReturnObject returnObject = new ReturnObject();

        if (!captcha.equals(session.getAttribute("captcha"))) {
            //登录失败,验证码错误
            returnObject.setCode(Constants.RETURN_OBJECT_CODE_FAIL);
            returnObject.setMessage("验证码错误");
        } else {
            //封装参数
            Map<String, Object> map = new HashMap<>();
            map.put("managerName", name);
            map.put("managerPassword", password);
            //调用service层方法，查询用户
            Manager manager = managerService.login(map);
            if (manager == null) {
                //登录失败,用户名或者密码错误
                returnObject.setCode(Constants.RETURN_OBJECT_CODE_FAIL);
                returnObject.setMessage("用户名或者密码错误");
            } else {//进一步判断账号是否合法
                if (manager.getManagerState().equals(Constants.STATE_DISABLED)) {
                    //登录失败，状态被锁定
                    returnObject.setCode(Constants.RETURN_OBJECT_CODE_FAIL);
                    returnObject.setMessage("状态被锁定");
                } else {
                    //登录成功
                    returnObject.setCode(Constants.RETURN_OBJECT_CODE_SUCCESS);
                    //把manager保存到session中
                    session.setAttribute(Constants.SESSION_USER, manager);
                }
            }
        }
        return returnObject;
    }
}